package com.qmyx.supply.admin.shiro;

import com.ytjj.qmyx.supplychain.mapper.entity.YxBanker;
import com.ytjj.qmyx.supplychain.service.BankerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;


/**
 * 自定义 Realm
 */
@Slf4j
public class BankerRealm extends AuthorizingRealm {
    @Autowired
    private BankerService bankerService;

    private final static String SALT="test**";

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //加这一步的目的是在Post请求的时候会先进认证，然后在到请求
        if (authenticationToken.getPrincipal() == null) {
            return null;
        }
        //获取用户手机号
        String tel = authenticationToken.getPrincipal().toString();
        YxBanker banker = bankerService.queryBankerByTel(tel);
        if (banker == null) {
            //这里返回后会报出对应异常
            return null;
        } else {
            //这里验证authenticationToken和simpleAuthenticationInfo的信息
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(tel, banker.getPwd(), getName());
            // 加盐的方式可随机字符
            simpleAuthenticationInfo.setCredentialsSalt(ByteSource.Util.bytes(SALT));
            return simpleAuthenticationInfo;
        }
    }
}
